/**
 * @swagger
 * tags:
 *   name: 考试记录
 *   description: 考试记录相关接口，包括开始考试、提交答案、查看成绩等
 */

/**
 * @swagger
 * components:
 *   schemas:
 *     Answer:
 *       type: object
 *       required:
 *         - question_id
 *         - answer
 *       properties:
 *         question_id:
 *           type: integer
 *           description: 题目ID
 *           example: 1
 *         answer:
 *           type: string
 *           description: |
 *             答案内容
 *             * 单选题：选项值（如 "A"）
 *             * 多选题：选项值数组的JSON字符串（如 ["A","B"]）
 *             * 判断题："true" 或 "false"
 *             * 问答题：文本答案
 *           example: "这是一个答案"
 *
 *     Grade:
 *       type: object
 *       required:
 *         - score
 *       properties:
 *         score:
 *           type: number
 *           description: |
 *             评分分值
 *             * 必须是非负数
 *             * 可以是小数（支持部分分）
 *           minimum: 0
 *           example: 8.5
 *         feedback:
 *           type: string
 *           description: |
 *             评分反馈
 *             * 可选字段
 *             * 用于给学生提供改进建议
 *           example: "论述较为全面，但缺少具体例子支撑"
 *
 *     ExamRecord:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: 考试记录ID
 *         exam_id:
 *           type: integer
 *           description: 考试ID
 *         student_id:
 *           type: integer
 *           description: 学生用户ID
 *         start_time:
 *           type: string
 *           format: date-time
 *           description: 开始答题时间
 *         submit_time:
 *           type: string
 *           format: date-time
 *           description: 提交时间
 *         status:
 *           type: string
 *           description: |
 *             考试状态
 *             * in_progress: 进行中
 *             * submitted: 已提交
 *             * timeout: 已超时
 *             * graded: 已评分
 *           enum: [in_progress, submitted, timeout, graded]
 *         total_score:
 *           type: number
 *           description: 考试总得分
 */

const express = require('express')
const { body, param, query } = require('express-validator')
const router = express.Router() // Can also use { mergeParams: true } if needed for examId context
const recordController = require('../controllers/recordController')
const { auth, requireRole } = require('../middleware/auth')
const { handleValidationErrors } = require('../middleware/validation')

// 学生开始/继续考试
router.post(
  '/exam/:examId/start',
  auth,
  requireRole(['student']), // Only students can start an exam for themselves
  param('examId').isInt().withMessage('考试ID必须是整数'),
  handleValidationErrors,
  recordController.startExam
)

// 学生提交单个答案
// :recordId refers to exam_record.id
router.post(
  '/:recordId/answer',
  auth,
  requireRole(['student']),
  param('recordId').isInt().withMessage('考试记录ID必须是整数'),
  [
    body('question_id').isInt().withMessage('题目ID必须是整数'),
    body('answer').exists().withMessage('答案不能为空'), // Further validation might depend on question type
  ],
  handleValidationErrors,
  recordController.submitAnswer
)

// 学生获取已保存的答案
// :recordId refers to exam_record.id
router.get(
  '/:recordId/answers',
  auth,
  requireRole(['student', 'admin']), // Admin might also need to see this during review
  param('recordId').isInt().withMessage('考试记录ID必须是整数'),
  handleValidationErrors,
  recordController.getAnswers
)

// 学生提交整个考试
// :recordId refers to exam_record.id
router.post(
  '/:recordId/submit',
  auth,
  requireRole(['student']),
  param('recordId').isInt().withMessage('考试记录ID必须是整数'),
  handleValidationErrors,
  recordController.submitExam
)

// 管理员获取某场考试的所有考试记录
router.get(
  '/exam/:examId',
  auth,
  requireRole(['admin']),
  param('examId').isInt().withMessage('考试ID必须是整数'),
  [
    // Validation for query parameters
    query('status')
      .optional()
      .isIn(['in_progress', 'submitted', 'timeout', 'graded'])
      .withMessage('无效的状态值'),
    query('page')
      .optional()
      .isInt({ min: 1 })
      .toInt()
      .withMessage('页码必须是正整数'),
    query('limit')
      .optional()
      .isInt({ min: 1, max: 100 })
      .toInt()
      .withMessage('每页数量必须在1-100之间'),
    query('username').optional().trim().escape(),
    query('name').optional().trim().escape(),
  ],
  handleValidationErrors,
  recordController.getExamRecords
)

// 获取单个学生考试记录的详细信息 (学生自己或管理员)
// :recordId refers to exam_record.id
router.get(
  '/:recordId/detail',
  auth, // Auth middleware handles if user is logged in
  param('recordId').isInt().withMessage('考试记录ID必须是整数'),
  handleValidationErrors,
  recordController.getStudentExamDetail // Controller will check if student owns record or if user is admin
)

// 管理员进行人工评分
// :recordId refers to exam_record.id
router.post(
  '/:recordId/question/:questionId/grade',
  auth,
  requireRole(['admin']),
  param('recordId').isInt().withMessage('考试记录ID必须是整数'),
  param('questionId').isInt().withMessage('题目ID必须是整数'),
  [
    body('score').isFloat({ min: 0 }).withMessage('分数必须是非负数字'), // Allow float for partial scores
    body('feedback').optional().trim(),
  ],
  handleValidationErrors,
  recordController.manualGrading
)

/**
 * @swagger
 * /api/records/exam/{examId}/start:
 *   post:
 *     summary: 开始考试
 *     description: |
 *       学生开始或继续一场考试
 *       * 仅学生可操作
 *       * 如果之前有未完成的考试记录，将返回该记录
 *       * 检查考试时间是否在有效期内
 *     tags: [考试记录]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: examId
 *         required: true
 *         description: 考试ID
 *         schema:
 *           type: integer
 *     responses:
 *       201:
 *         description: 成功开始考试
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ExamRecord'
 *       400:
 *         description: |
 *           开始考试失败
 *           * 考试ID无效
 *           * 考试未开始或已结束
 *       403:
 *         description: |
 *           权限不足
 *           * 不是学生用户
 *           * 已参加过该考试
 */

/**
 * @swagger
 * /api/records/{recordId}/answer:
 *   post:
 *     summary: 提交答案
 *     description: |
 *       学生提交单个题目的答案
 *       * 仅学生可操作
 *       * 支持自动保存
 *       * 验证答题时间是否在考试时间内
 *     tags: [考试记录]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: recordId
 *         required: true
 *         description: 考试记录ID
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/Answer'
 *     responses:
 *       200:
 *         description: 答案提交成功
 *       400:
 *         description: |
 *           提交失败
 *           * 题目ID无效
 *           * 答案格式错误
 *       403:
 *         description: |
 *           提交被拒绝
 *           * 不是本人的考试记录
 *           * 考试时间已结束
 */

/**
 * @swagger
 * /api/records/{recordId}/answers:
 *   get:
 *     summary: 获取答案记录
 *     description: |
 *       获取学生在某次考试中的所有答案
 *       * 学生可查看自己的答案
 *       * 管理员可查看所有学生的答案
 *     tags: [考试记录]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: recordId
 *         required: true
 *         description: 考试记录ID
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: 成功获取答案记录
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/Answer'
 *       403:
 *         description: 无权查看此考试记录
 *       404:
 *         description: 考试记录不存在
 */

/**
 * @swagger
 * /api/records/{recordId}/submit:
 *   post:
 *     summary: 提交考试
 *     description: |
 *       学生提交整场考试
 *       * 仅学生可操作
 *       * 提交后不可再修改答案
 *       * 自动进行客观题评分
 *     tags: [考试记录]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: recordId
 *         required: true
 *         description: 考试记录ID
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: 考试提交成功
 *       400:
 *         description: |
 *           提交失败
 *           * 考试记录ID无效
 *           * 考试已提交
 *       403:
 *         description: 无权提交此考试
 */

/**
 * @swagger
 * /api/records/exam/{examId}:
 *   get:
 *     summary: 获取考试记录列表
 *     description: |
 *       管理员获取某场考试的所有考试记录
 *       * 仅管理员可访问
 *       * 支持分页查询
 *       * 支持按状态筛选
 *       * 支持按学生信息搜索
 *     tags: [考试记录]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: examId
 *         required: true
 *         description: 考试ID
 *         schema:
 *           type: integer
 *       - in: query
 *         name: status
 *         description: |
 *           考试状态筛选
 *           * in_progress: 进行中
 *           * submitted: 已提交
 *           * timeout: 已超时
 *           * graded: 已评分
 *         schema:
 *           type: string
 *           enum: [in_progress, submitted, timeout, graded]
 *       - in: query
 *         name: page
 *         description: 页码（从1开始）
 *         schema:
 *           type: integer
 *           minimum: 1
 *       - in: query
 *         name: limit
 *         description: 每页记录数（1-100）
 *         schema:
 *           type: integer
 *           minimum: 1
 *           maximum: 100
 *       - in: query
 *         name: username
 *         description: 按用户名搜索
 *         schema:
 *           type: string
 *       - in: query
 *         name: name
 *         description: 按姓名搜索
 *         schema:
 *           type: string
 *     responses:
 *       200:
 *         description: 成功获取考试记录列表
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 records:
 *                   type: array
 *                   items:
 *                     $ref: '#/components/schemas/ExamRecord'
 *                 total:
 *                   type: integer
 *                   description: 总记录数
 *                 page:
 *                   type: integer
 *                   description: 当前页码
 *                 limit:
 *                   type: integer
 *                   description: 每页记录数
 */

/**
 * @swagger
 * /api/records/{recordId}/detail:
 *   get:
 *     summary: 获取考试记录详情
 *     description: |
 *       获取考试记录的详细信息
 *       * 学生可查看自己的记录
 *       * 管理员可查看所有记录
 *       * 包含答题详情和评分信息
 *     tags: [考试记录]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: recordId
 *         required: true
 *         description: 考试记录ID
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: 成功获取考试记录详情
 *         content:
 *           application/json:
 *             schema:
 *               allOf:
 *                 - $ref: '#/components/schemas/ExamRecord'
 *                 - type: object
 *                   properties:
 *                     answers:
 *                       type: array
 *                       items:
 *                         $ref: '#/components/schemas/Answer'
 *       403:
 *         description: 无权查看此考试记录
 *       404:
 *         description: 考试记录不存在
 */

/**
 * @swagger
 * /api/records/{recordId}/question/{questionId}/grade:
 *   post:
 *     summary: 评分
 *     description: |
 *       管理员对试题进行人工评分
 *       * 仅管理员可操作
 *       * 主要用于主观题评分
 *       * 可以给出评分反馈
 *     tags: [考试记录]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: recordId
 *         required: true
 *         description: 考试记录ID
 *         schema:
 *           type: integer
 *       - in: path
 *         name: questionId
 *         required: true
 *         description: 题目ID
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/Grade'
 *     responses:
 *       200:
 *         description: 评分成功
 *       400:
 *         description: |
 *           评分失败
 *           * 分数无效
 *           * 题目不存在
 *       403:
 *         description: 权限不足，需要管理员权限
 *       404:
 *         description: 考试记录不存在
 */

module.exports = router
